<template>
    <div ref="topMenusBox" :class="{ unvisiable: !showMenu }" class="menus-box">
        <div style="width: 182px; padding: 10px 0; text-align: center">
            <el-input
                ref="input"
                :placeholder="language=='en'?'Search menu':'查找菜单名称'"
                v-model.trim="keyWord"
                clearable
                style="width: 136px"
                suffix-icon="el-icon-search"
                @change="serchKeyWord"
            />
        </div>
        <button type="button" class="el-dialog__headerbtn" @click="closeTopMenu">
            <em class="el-icon el-icon-close"/>
        </button>
        <el-cascader-panel
            v-model="currentChoosed"
            :options="options"
            @change="handleClickMenu"
        />
    </div>
</template>
<script>
import { findStudentCultureRelById } from 'common/src/api/culture/culturePlan'
import mixin from 'common/src/mixins/index'
export default {
    name: 'TopMenu',
    mixins: [mixin],
    props: ['showMenu', 'menus'],
    data() {
        return {
            keyWord: '',
            options: [],
            menuList: [],
            currentChoosed: null,
            index: null
        }
    },
    computed: {
        language() {
            return this.$store.getters.language
        }
    },
    created() {
        this.menuList = _.cloneDeep(this.menus.menuItems)
        this.options = this.cycle(this.menuList)
        this.index = null
    },
    mounted() {
        const inputNode = document.querySelector('.menus-box').firstChild
        const node = document.querySelector('.el-cascader-menu__list')
        node.insertBefore(inputNode, node.firstChild)
    },
    methods: {
        /**
         * keyWord 搜索关键词
         * 匹配规则
         * 高亮：模糊匹配所有菜单，取匹配到的第一个菜单作为高亮显示
         * 过滤：模糊匹配所有菜单，对比过滤原始菜单和匹配到的菜单
         */
        serchKeyWord(keyWord) {
            const storageList = this.cycle(this.menuList.filter(f => f.parentAuthId === -1))
            this.index = null
            this.currentChoosed = null
            if (!keyWord) {
                this.options = storageList
            } else {
                const vagueList = []
                const fn = (array = [], keyWord = '') => {
                    array.forEach((item) => {
                        if (item.children) fn(item.children, keyWord)
                        if (item.label.indexOf(keyWord) !== -1) {
                            vagueList.push(item)
                        }
                    })
                }
                fn(storageList, keyWord)
                if (!vagueList.length) {
                    this.options = []
                } else {
                    this.currentChoosed = vagueList[0] && vagueList[0].value
                    // 过滤一级菜单
                    this.options = storageList.filter((item, index) => {
                        return vagueList.findIndex((vag) => vag.index == index + 1) !== -1
                    })
                }
            }
        },
        /**
         * 循环函数
         * array：需要循环的数组
         * incomingFn 传入的循环体
         * privateFn 内嵌默认循环体
         */
        cycle(array = [], incomingFn) {
            const _this = this
            const privateFn = (item) => {
                const obj = {
                    label: this.language == 'en' ? item.authNameEn : item.authNameCh,
                    value: item.urlPath,
                    index: item.parentAuthId === -1 ? ++this.index : this.index
                }
                if (item.children) obj.children = _this.cycle(item.children)
                return obj
            }
            return array.map(incomingFn || privateFn)
        },
        handleClickMenu(menuList) {
            const currentMenu = menuList[menuList.length - 1]
            // 获取当前激活页签并存入sessionStorage
            let menuItem
            const match = function(array = [], url = '') {
                array.some((cur) => {
                    if (cur.urlPath === url) {
                        menuItem = cur
                        return true
                    }
                    if (cur.children) match(cur.children, url)
                })
            }
            match(this.menuList, currentMenu)
            sessionStorage.setItem('menuItem', JSON.stringify(menuItem))
            // 判断当前路由是否需要特殊处理
            this.judgeCurrentMent(currentMenu, (cb) => {
                if (!cb) {
                    this.$router.replace({
                        path: currentMenu
                    })
                }
            })
            /**
             * 原本的关闭菜单方法，只是用于点击菜单节点（topMenusBox）之外的部分时，关闭菜单，这里不适用。
             * 路由改变，会触发Navbar里的watch方法自动隐藏菜单。
             */
            // this.closeTopMenu(!this.showMenu)
        },
        async toMyPlan() {
            const { code, data } = await findStudentCultureRelById(this.global.currentUser.uid)
            if (code !== 200) return
            this.$router.replace({
                path: `/personalPlanDetail/${this.global.currentUser.uid}`,
                query: {
                    templateId: data.cultureId
                }
            })
        },
        /**
         * 判断当前路由是否需要特殊处理
         * eg: 我的培养方案
         * path :当前路由
         * cb:回调函数
         */
        judgeCurrentMent(path, cb) {
            let hasPath = ''
            const actions = new Map()
            // 需要特殊处理的路由跳转在此处添加
            actions.set('/personalPlanDetail', this.toMyPlan)
            hasPath = actions.has(path)
            if (hasPath) {
                return actions.get(path)()
            } else {
                cb(hasPath)
            }
        },
        closeTopMenu(status) {
            this.$emit('change-visiable', status)
        }
    }
}
</script>
<style lang="scss" scoped>
.unvisiable {
    height: 0;
}
.menus-box {
    ::v-deep {
        .el-cascader-menu__wrap {
            height: 100%;
        }
        .el-scrollbar {
            height: calc(100vh - 80px);
        }
        .el-cascader-menu{
            min-width: 210px;
        }
        .in-active-path {
            // border-left: 4px solid #3a7fe8;
            background: rgba(58, 127, 232, 0.25);
            color: none;
        }
        .is-active {
            border-left: 4px solid #3a7fe8;
            background: rgba(58, 127, 232, 0.25);
            color: none;
        }
        .el-input__inner {
            width: 136px;
            height: 35px;
            border-radius: 35px;
            background: #edf1f5;
        }
        .el-dialog__headerbtn {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 0;
            background: 0 0;
            border: none;
            outline: 0;
            cursor: pointer;
            font-size: 16px;
        }
        .el-cascader-node {
              padding-right: 30px;
        }
    }
}
</style>

